package com.example.libary.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * JWT工具类
 */
@Slf4j
@Component
public class JwtUtil {
    
    @Value("${jwt.secret}")
    private String secret;
    
    @Value("${jwt.expiration}")
    private Long expiration;
    
    /**
     * 生成token
     *
     * @param username 用户名
     * @return token
     */
    public String generateToken(String username) {
        log.debug("为用户 {} 生成token", username);
        Map<String, Object> claims = new HashMap<>();
        String token = createToken(claims, username);
        log.debug("生成的token: {}", token);
        return token;
    }
    
    /**
     * 从token中获取用户名
     *
     * @param token token
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        try {
            String username = getClaimFromToken(token, Claims::getSubject);
            log.debug("从token中获取用户名: {}", username);
            return username;
        } catch (Exception e) {
            log.error("获取用户名异常", e);
            return null;
        }
    }
    
    /**
     * 验证token
     *
     * @param token token
     * @return 是否有效
     */
    public Boolean validateToken(String token) {
        try {
            log.debug("开始验证token");
            final String username = getUsernameFromToken(token);
            boolean valid = (username != null && !isTokenExpired(token));
            log.debug("token验证结果: {}", valid);
            return valid;
        } catch (ExpiredJwtException e) {
            log.error("Token已过期", e);
            return false;
        } catch (UnsupportedJwtException e) {
            log.error("不支持的JWT格式", e);
            return false;
        } catch (MalformedJwtException e) {
            log.error("JWT格式错误", e);
            return false;
        } catch (SignatureException e) {
            log.error("JWT签名验证失败", e);
            return false;
        } catch (Exception e) {
            log.error("JWT验证异常", e);
            return false;
        }
    }
    
    /**
     * 判断token是否过期
     *
     * @param token token
     * @return 是否过期
     */
    private Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getExpirationDateFromToken(token);
            boolean expired = expiration.before(new Date());
            log.debug("token过期时间: {}, 是否过期: {}", expiration, expired);
            return expired;
        } catch (Exception e) {
            log.error("检查token是否过期异常", e);
            return true;
        }
    }
    
    /**
     * 从token中获取过期时间
     *
     * @param token token
     * @return 过期时间
     */
    private Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }
    
    /**
     * 从token中获取指定的claim
     *
     * @param token          token
     * @param claimsResolver 解析函数
     * @param <T>            返回类型
     * @return claim
     */
    private <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }
    
    /**
     * 从token中获取所有的claims
     *
     * @param token token
     * @return claims
     */
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
    
    /**
     * 创建token
     *
     * @param claims  claims
     * @param subject 主题
     * @return token
     */
    private String createToken(Map<String, Object> claims, String subject) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + expiration);
        log.debug("创建token, 主题: {}, 过期时间: {}", subject, expirationDate);
        
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }
    
    /**
     * 获取签名密钥
     *
     * @return 签名密钥
     */
    private Key getSigningKey() {
        try {
            log.debug("获取签名密钥");
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] keyBytes = md.digest(secret.getBytes(StandardCharsets.UTF_8));
            return Keys.hmacShaKeyFor(keyBytes);
        } catch (NoSuchAlgorithmException e) {
            log.error("获取签名密钥异常，使用默认方法", e);
            return Keys.secretKeyFor(SignatureAlgorithm.HS256);
        }
    }
} 